package api

import (
	"chatbot-api-go/domain/zsxq/models"
	"encoding/json"
	"fmt"
	"go.uber.org/zap"
	"io"
	"net/http"
	"strings"
)

// ZsxqApi 知识星球 API 接口
type ZsxqApi interface {
	QueryUnAnsweredQuestionsTopicId(groupId string, cookie string) (resp models.UnAnsweredQuestionsAggregates, err error)
	Answer(groupId string, cookie string, topicId string, text string, silenced bool) (success bool, err error)
}

func QueryUnAnsweredQuestionsTopicId(groupId, cookie string) (resp models.UnAnsweredQuestionsAggregates, err error) {
	getUrl := fmt.Sprintf("https://api.zsxq.com/v2/groups/%s/topics?scope=unanswered_questions&count=20", groupId)
	req, _ := http.NewRequest("GET", getUrl, nil)
	req.Header.Add("cookie", cookie)
	req.Header.Add("Content-Type", "application/json;charset=utf8")
	response, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()

	body, err := io.ReadAll(response.Body)
	if err != nil {
		panic(err)
	}
	result := models.UnAnsweredQuestionsAggregates{}
	err = json.Unmarshal(body, &result)
	if err != nil {
		zap.S().Errorw("【QueryUnAnsweredQuestionsTopicId】序列化问答返回值失败",
			"msg",
			err.Error(),
		)
	}
	return result, nil
}

func Answer(groupId string, cookie string, topicId int, text string, silenced bool) (success bool, err error) {
	postUrl := fmt.Sprintf("https://api.zsxq.com/v2/topics/%d/answer", topicId)
	reqData := models.ReqData{
		Text:     text,
		ImageIds: []string{},
		Silenced: silenced,
	}
	entity := models.AnswerReq{ReqData: reqData}
	jsonStr, err := json.Marshal(entity)
	resStr := string(jsonStr)
	req, _ := http.NewRequest("POST", postUrl, strings.NewReader(resStr))

	req.Header.Add("cookie", cookie)
	req.Header.Add("Content-Type", "application/json;charset=utf8")
	req.Header.Add("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36")

	response, err := http.DefaultClient.Do(req)

	if response.StatusCode != http.StatusOK {
		zap.S().Errorw("【Answer】回复问题Api调用失败",
			"msg",
			err.Error(),
		)
	}
	zap.S().Infof(`回答问题结果。groupId：%s topicId：%d jsonStr：%s`, groupId, topicId, response.Body)
	return true, nil
}
